package com.ruoyi.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.account.service.IAccountMerchantInfoService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.db.domain.AccountMerchantInfo;
import com.ruoyi.db.domain.MerchantBaseInfo;
import com.ruoyi.db.domain.MerchantUserInfo;
import com.ruoyi.db.domain.SysDeptCopy;
import com.ruoyi.laiqianba.enums.InfoTypeEnum;
import com.ruoyi.merchant.constant.MerchantConstant;
import com.ruoyi.merchant.service.IMerchantBaseInfoService;
import com.ruoyi.merchant.service.ISysDeptCopyService;
import com.ruoyi.merchantdata.service.IMerchantUserInfoService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.service.IMerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;

@Service
public class MerchantService implements IMerchantService {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IMerchantUserInfoService merchantUserInfoService;
    @Autowired
    private IMerchantBaseInfoService merchantBaseInfoService;
    @Autowired
    private IAccountMerchantInfoService accountMerchantInfoService;
    @Autowired
    private ISysDeptCopyService sysDeptCopyService;

    /**
     * 新增机构员工接口
     */
    @Override
    public AjaxResult insertMerchatUser(MerchantUserInfo merchantUserInfo) {
        Long deptId = SecurityUtils.getDeptId();

        SysUser sysUser = new SysUser();
        sysUser.setDeptId(deptId);

        String phone = merchantUserInfo.getPhone();
        sysUser.setUserName(phone);
        sysUser.setPhonenumber(phone);

        String password = phone.substring(phone.length() - 6); // 提取后6位
        String pwd = SecurityUtils.encryptPassword(password);
        sysUser.setPassword(pwd);

        sysUser.setNickName(merchantUserInfo.getNickName());
        sysUser.setCreateBy(getUsername());

        //查询出InfoId
        Long InfoId = merchantBaseInfoService.seletInfoIdBydeptId(deptId);
        merchantUserInfo.setInfoId(InfoId);

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.selectMerchantBaseInfoById(InfoId);
        String infoType = merchantBaseInfo.getInfoType();
        if(StringUtils.equals(InfoTypeEnum.CRM.getValue(),infoType)){
            sysUser.setRoleIds(new Long[]{MerchantConstant.MERCHANT_ROLEID_CRM_STAFF});
        }else {
            sysUser.setRoleIds(new Long[]{MerchantConstant.MERCHANT_ROLEID_API_STAFF});
        }

        //检查手机号码
        if (StringUtils.isNotEmpty(merchantUserInfo.getPhone()) && !userService.checkPhoneUnique(sysUser)) {
            return AjaxResult.error("手机号已经存在");
        }
        int i = userService.insertUser(sysUser);
        if (i <= 0) {
            return AjaxResult.error("新增用户登陆信息失败");
        }
        merchantUserInfo.setUid(sysUser.getUserId());
        merchantUserInfo.setDeptId(deptId);

        int i1 = merchantUserInfoService.insertMerchantUserInfo(merchantUserInfo);
        if (i1 > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error("添加业务员失败");
    }

    @Override
    public AjaxResult deleUser(long userId) {

        String newPhone = RandomUtil.randomNumbers(11);

        SysUser sysUser = userService.selectUserById(userId);
        sysUser.setPhonenumber(newPhone);
        sysUser.setUserName(newPhone);
        sysUser.setStatus("1");

        if (!userService.checkPhoneUnique(sysUser)) {
            return AjaxResult.error("删除失败，请重新尝试");
        }

        int i = userService.updateUser(sysUser);

        if (i > 0) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败，请联系管理员");
    }


    /**
     * 机构管理员修改员工登录状态
     */
    @Override
    public int updateUserStatus(MerchantUserInfo merchantUserInfo) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(merchantUserInfo.getUid());
        sysUser.setStatus(merchantUserInfo.getStatus());
        int i = userService.updateUserStatus(sysUser);
        return merchantUserInfoService.updateMerchantUserInfo(merchantUserInfo);
    }

    /*
    新增 CRM  机构逻辑
     */
    @Override
    public AjaxResult insertMerchantBaseInfo(MerchantBaseInfo merchantBaseInfo) {

        //
        SysDeptCopy sysDeptCopy = this.addMerchantDeptInfo(merchantBaseInfo.getInfoName());
        if (ObjectUtil.isEmpty(sysDeptCopy)) {
            return AjaxResult.error("新增机构部门信息失败");
        }

        // 新增部门管理员信息
        String loginName = RandomUtil.randomNumbers(9);
        String loginPwd = RandomUtil.randomString(6);
        merchantBaseInfo.setAdminName(loginName);
        merchantBaseInfo.setAdminPwd(loginPwd);
        merchantBaseInfo.setDeptId(sysDeptCopy.getDeptId());
        SysUser sysUser = this.addMerchantManagerInfo(sysDeptCopy, merchantBaseInfo);
        if (ObjectUtil.isEmpty(sysUser)) {
            return AjaxResult.error("新增机构管理员信息失败");
        }

        MerchantBaseInfo newMerchantBaseInfo = merchantBaseInfoService.saveMerchantBaseInfo(merchantBaseInfo);
        if (ObjectUtil.isEmpty(newMerchantBaseInfo)) {
            return AjaxResult.error("新增机构基本信息失败");
        }

        // 生成账户信息
        AccountMerchantInfo accountMerchantInfo = new AccountMerchantInfo();
        accountMerchantInfo.setInfoId(newMerchantBaseInfo.getId());
        int i = accountMerchantInfoService.insertAccountMerchantInfo(accountMerchantInfo);
        if (i < 1) {
            return AjaxResult.error("新增机构账户信息失败");
        }

        return AjaxResult.success();
    }

    /**
     * 新增机构部门信息
     *
     * @param infoName
     * @return
     */
    public SysDeptCopy addMerchantDeptInfo(String infoName) {

        String randomStr = RandomUtil.randomString(3);
        infoName = infoName + randomStr;
        // 生成部门信息
        SysDeptCopy sysDept = new SysDeptCopy();
        sysDept.setDeptName(infoName);
        sysDept.setParentId(MerchantConstant.MERCHANT_PARENT_DEPT_ID);
        sysDept.setOrderNum(100);
        SysDeptCopy sysDeptCopy = sysDeptCopyService.saveInfo(sysDept);
        return sysDeptCopy;
    }

    /**
     * 新增机构管理员
     *
     * @param sysDeptCopy
     * @param merchantBaseInfo
     * @return
     */
    public SysUser addMerchantManagerInfo(SysDeptCopy sysDeptCopy, MerchantBaseInfo merchantBaseInfo) {
        //创建用户
        SysUser sysUser = new SysUser();
        sysUser.setNickName(merchantBaseInfo.getInfoName());
        sysUser.setUserName(merchantBaseInfo.getAdminName());
        //密码加密
        String passward = SecurityUtils.encryptPassword(merchantBaseInfo.getAdminPwd());
        sysUser.setPassword(passward);

        sysUser.setNickName(merchantBaseInfo.getInfoName());
        sysUser.setDeptId(sysDeptCopy.getDeptId());

        if (StringUtils.equals(merchantBaseInfo.getInfoType(), "CRM")) {
            sysUser.setRoleId(MerchantConstant.MERCHANT_ROLEID_CRM_MANAGER);
            sysUser.setRoleIds(new Long[]{MerchantConstant.MERCHANT_ROLEID_CRM_MANAGER});
        } else {
            sysUser.setRoleId(MerchantConstant.MERCHANT_ROLEID_API_MANAGER);
            sysUser.setRoleIds(new Long[]{MerchantConstant.MERCHANT_ROLEID_API_MANAGER});
        }
        int i = userService.insertUser(sysUser);
        if (i > 0) {
            return sysUser;
        }
        return null;
    }


}
